<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="flex justify-around m-auto w-300px">
      <Select
        :options="selectOptions"
        style="width: 180px"
        v-model:value="currentCode"
        @change="handleSelected"
      />
      <a-button type="primary" @click="customSubmitFunc" class="ml-2">保存</a-button>
      <a-button type="primary" @click="handleDesign" class="ml-2">设计器</a-button>
    </div>
    <div class="w-full m-auto mt-2 pl-2 pr-2">
      <AceEditor v-model:value="scriptStr" :readonly="false" />
    </div>
  </ScrollContainer>
  <DesignIframe ref="ifrmRef" @register="registerDesignIframeView" @success="handleSuccess" />
</template>

<script lang="ts" setup>
  import { ref, unref, onUnmounted, onMounted } from 'vue';
  import { ScrollContainer } from '/@/components/Container';
  import { Select } from 'ant-design-vue';
  import DesignIframe from './modules/DesignIframe.vue';
  import { useModal } from '/@/components/Modal';
  import { AceEditor } from '/@/components/AceEditor/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import { getVisualGetScript, getVisualUpdateScript } from '/@/api/formDesign/formDesign';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const props = defineProps({
    formCode: {
      type: String,
      default: '',
    },
  });
  const ifrmRef: any = ref(null);
  const userStore = useUserStore();
  const { t } = useI18n();
  const scriptStr = ref('');
  const loading = ref(false);
  const currentCode = ref('preProcess');
  const selectOptions = ref([
    {
      value: 'preProcess',
      label: '预处理事件',
    },
    {
      value: 'validate',
      label: '验证事件',
    },
    {
      value: 'see',
      label: '查看事件',
    },
    {
      value: 'create',
      label: '添加事件',
    },
    {
      value: 'save',
      label: '修改事件',
    },
    // {
    //   value: 'preDispose',
    //   label: '节点预处理事件',
    // },
    {
      value: 'del',
      label: '删除事件',
    },
    {
      value: 'form_js',
      label: '前台脚本',
    },
    {
      value: 'import_validate',
      label: '导入前验证事件',
    },
    {
      value: 'import_create',
      label: '导入后事件',
    },
  ]);
  //节点事件
  const flowNodeArr = ['validate', 'preDispose', 'actionActive', 'actionFinish', 'actionReturn'];
  const [registerDesignIframeView, { openModal, closeModal }] = useModal();
  const customSubmitFunc = async () => {
    try {
      let values: any = {
        script: unref(scriptStr),
        moduleCode: props.formCode,
        eventType: unref(currentCode),
      };
      loading.value = true;
      console.log(values);
      await getVisualUpdateScript(values);
      createMessage.success(t('common.opSuccess'));
      getAdminFlowGetEventScriptData();
      loading.value = false;
    } catch (err) {
      console.log(err);
    } finally {
      loading.value = false;
    }
  };

  const getAdminFlowGetEventScriptData = async () => {
    if (!unref(currentCode)) {
      scriptStr.value = '';
      return;
    }
    const params: any = {
      moduleCode: props.formCode,
      eventType: unref(currentCode),
    };

    const { script } = await getVisualGetScript(params);
    scriptStr.value = script;
  };

  const fetch = () => {
    getAdminFlowGetEventScriptData();
  };

  //change
  const handleSelected = () => {
    getAdminFlowGetEventScriptData();
  };

  onMounted(() => {
    fetch();
  });

  //设计器
  const handleDesign = () => {
    openModal(true, {
      scriptStr: unref(scriptStr),
      formCode: props.formCode,
    });
  };

  //回调
  const handleSuccess = (value) => {
    console.log('handleSuccess', value);
    if (value) {
      scriptStr.value = value;
    }
  };

  let ideUrl = 'script_frame.jsp';
  const onMessage = (e) => {
    var d = e.data;
    var data = d.data;
    var type = d.type;
    if (type == 'setScript') {
      console.log('onMessage data', data);
      scriptStr.value = data;
      if (d.cwsToken != null) {
        let cwsToken = d.cwsToken;
        ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
      }
      closeModal();
    } else if (type == 'getScript') {
      let serverInfo = userStore.getServerInfo;
      console.log('getScript scriptStr.value=', scriptStr.value);
      let data = {
        type: 'openerScript',
        version: serverInfo.version,
        spVersion: serverInfo.spVersion,
        scene: 'module.' + currentCode.value,
        data: scriptStr.value,
      };
      // window.postMessage(data, '*');
      unref(ifrmRef).doPostMessage(data);
    } else if (type == 'setCwsToken') {
      let cwsToken = d.cwsToken;
      ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
    }
  };

  if (window.addEventListener) {
    // all browsers except IE before version 9
    window.addEventListener('message', onMessage, false);
  }

  onUnmounted(() => {
    console.log('EventDesign-onUnmounted');
    window.removeEventListener('message', onMessage, false);
  });
</script>
